<?php
/**
 * 发送个性短信
 * @Author: lf
 */
namespace app\admin\controller;

use app\admin\model\Channel;
use app\services\MqInsertService;
use think\Db;
use think\facade\Env;

class SendSelfdom extends Father
{
    public function index()
    {
        // if(session('user_type') != 'admin'){
        //     return '升级中';
        // }
        $this->assign('cha', Channel::withSearch(['off_redis'])->field('channel_id,company_name')->select());
        $this->assign('thistime', date('Y-m-d H:i:s', time() + 300));
        //需求：自定义注意事项
        $this->assign('send_attentiontxt', cache('send_attentiontxt3')); //用于展示
        if (cache('send_attentiontxt3')) {
            $this->assign('send_attentiontxt_e', addslashes(implode("\r\n", cache('send_attentiontxt3')))); //用于编辑
        } else {
            $this->assign('send_attentiontxt_e', ''); //用于编辑
        }

        return $this->fetch();
    }

    /**
     * 接收文件
     * @Author   lf
     * @DateTime 2019-09-11T14:20:42+0800
     * @return   [type]                   [description]
     */
    public function upflie()
    {
        $sms_y       = input('post.sms_y'); //类别
        $is_dingshi  = input('post.is_dingshi'); //是否定时
        $dingshitime = input('post.dingshitime'); //定时时间
        $message     = input('post.message'); //备注
        $postUrl     = ''; //最终提交的地址
        if (session('user_type') != 'admin') {
            //$isVideo==0 是视频短信
            $isVideo = Db::table("bus_channel")->where('channel_id', session("relate_id"))->value("off_redis");
            if ($isVideo == 0) {
                $sms_y = 2;
            } else {
                $sms_y = 1;
            }
        }

        if ($is_dingshi && !(date('Y-m-d H:i:s', strtotime($dingshitime)) == $dingshitime)) {
            return json(['code' => 0, 'msg' => "提交错误：请选择定时时间"]);
        }

        //管理员发送短信不需要绑定渠道
        if (session('user_type') == 'admin') {
            $cid = trim(input('post.cha'));
            if (!$cid) {
                return json(['code' => 0, 'msg' => "提交错误：请选择用户"]);
            }
        } else {
            //是否渠道账号
            if (session('user_type') != 'channel') {
                return json(['code' => 0, 'msg' => "提交错误：该账户不是用户账号"]);
            }
            //是否绑定渠道
            if (empty(session('relate_id'))) {
                return json(['code' => 0, 'msg' => "提交错误：该账号没有绑定用户"]);
            }
            //是否绑定渠道
            if (Channel::get(['channel_id' => session('relate_id'), 'status' => '0'])) {
                return json(['code' => 0, 'msg' => "提交错误：已禁用，请联系管理员"]);
            }
            $cid = session('relate_id');
        }

        // 获取表单上传文件
        $file = request()->file('phonesfile');
        // 移动到框架应用根目录/public/uploads/sendnote 目录下
        if ($file) {
            $info = $file->validate(['size' => 21 * 1024 * 1024, 'ext' => 'xlsx'])->move(Env::get("root_path") . 'public/uploads/sendnote');
            if ($info) {
                $infos = $info->getInfo();
                // 成功上传后 获取上传信息
                $savename = Env::get("root_path") . 'public/uploads/sendnote/' . $info->getSaveName();
                trace('用户' . session('username') . '文件导入提交号码，保存在服务器的文件：' . $savename . '，原文件名：' . $infos['name']);
                trace('备注:' . $message);

                //检查文件格式
                require_once Env::get('vendor_path') . 'PHPExcel/PHPExcel.php';

                $excelType   = \PHPExcel_IOFactory::identify($savename);
                $excelReader = \PHPExcel_IOFactory::createReader($excelType);

                $excelFilter           = new PHPExcelReadFilter();
                $excelFilter->startRow = 1; //只取第一第二行
                $excelFilter->endRow   = 2; //只取第一第二行
                $excelReader->setReadFilter($excelFilter);
                $phpexcel = $excelReader->load($savename);
                $sheet    = $phpexcel->getActiveSheet();

                $highestColumm = $sheet->getHighestColumn(); // 取得总列数

                trace('取得总列数' . $highestColumm);

                for ($i = 'A'; $i <= $highestColumm; $i++) {
                    // 1.列数检查，以每列第一个cell有没有填标题为准，必须每列都需要有标题
                    if (empty($sheet->getCell($i . '1')->getValue())) {
                        return json(['code' => 0, 'msg' => $i . "列的标题不能为空，如果是空列请删除"]);
                    }

                    // 2.每列的第一个cell的属性是不是常规
                    if ($sheet->getStyle($i . '1')->getNumberFormat()->getFormatCode() != 'General') {
                        return json(['code' => 0, 'msg' => $i . "1 单元格不是常规格式，请设置excel表格{$i}列的单元格格式为常规"]);
                    }
                    // 3.每列的第二个cell有没有填充内容(空格去掉)
                    if (empty($sheet->getCell($i . '2')->getValue())) {
                        return json(['code' => 0, 'msg' => "{$i}2单元格不能为空，如果该列不需要请删除"]);
                    }
                }

                switch ($sms_y) {
                    case '1':
                        $order_type = 3; //个性定时
                        $postUrl    = 'http://119.91.61.33:8080/SMS/upload/gx/pt';
                        break;
                    case '2':
                        $order_type = 4; //个性视频定时
                        $postUrl    = 'http://119.91.61.33:8080/SMS/upload/gx/sp';
                        break;

                    default:
                        return json(['code' => 101, 'msg' => " -- 上传失败"]);
                        break;
                }
                //定时--------------------------------------------------------------------------------
                if ($is_dingshi) {
                    return $this->fundingshi($dingshitime, $order_type, $sms_y, $cid, $savename, $message);
                }
                //定时--------------------------------------------------------------------------------

                //文件发送--------------------------------------------------------------------------------
                $post_data = array(
                    'file' => new \CURLFile(realpath($savename))
                    , 'cid' => $cid,
                );

                $result = $this->curlSms($postUrl, $post_data);

                if ($result['result']['code'] == 200) {
                    //添加记录
                    Db('bus_selfdom_info')->insert([
                        'sms_type'    => $sms_y,
                        'batch_num'   => $result['result']['order_id'],
                        'channel_id'  => $cid,
                        'username'    => session('username'),
                        'send_time'   => date('Y-m-d H:i:s'),
                        'create_time' => date('Y-m-d H:i:s'),
                        'save_name'   => $savename,
                        'message'     => $message,
                    ]);
                    return json(['code' => 200, 'msg' => "发送成功，批次【" . $result['result']['order_id'] . "】请在个性查询中查看最终结果"]);
                } else {
                    trace("上传错误" . $result['error'], "send");
                    return json(['code' => 0, 'msg' => "发送失败"]);
                }
                //文件发送--------------------------------------------------------------------------------

            } else {
                // 上传失败获取错误信息
                trace($file->getError());
                return json(['code' => 0, 'msg' => $file->getError()]);
            }
        } else {
            return json(['code' => 0, 'msg' => "提交错误：文件为空"]);
        }
        return json(['code' => 0, 'msg' => "提交错误,请联系管理员"]);
    }

    /**
     * 加入定时
     * @param  [type] $dingshitime [description]
     * @param  [type] $order_type  [description]
     * @param  [type] $sms_y       [description]
     * @param  [type] $cid         [description]
     * @param  [type] $savename    [description]
     * @return [type]              [description]
     */
    public function fundingshi($dingshitime, $order_type, $sms_y, $cid, $savename, $message)
    {
        // $batch_num = uniqid().rand(100,999);
        $send_time = $dingshitime;
        //添加记录$selfdom_info_id = db('bus_selfdom_info')->insertGetId($data);
        $selfdom_info_id = Db('bus_selfdom_info')->insertGetId([
            // 'order_type'  => $order_type,
            'sms_type'    => $sms_y,
            // 'batch_num'   => $batch_num,
            'channel_id'  => $cid,
            'username'    => session('username'),
            'send_time'   => $send_time,
            'create_time' => date('Y-m-d H:i:s'),
            'save_name'   => $savename,
            'message'     => $message,
        ]);

        if ($selfdom_info_id) {
            $mqinsert       = new MqInsertService('sendtask', 'app\Job\SendSelfdomJob');
            $mqinsertReslut = $mqinsert->addJob(['id' => $selfdom_info_id]);

            trace('队列结果：' . $mqinsertReslut);
            return json(['code' => 200, 'msg' => date('Ymd-H:i:s') . " -- 上传成功"]);
        }

        return json(['code' => 200, 'msg' => date('Ymd-H:i:s') . " -- 上传失败"]);
    }

    /**
     * 发送短信
     * @param  [type] $postUrl   [description]
     * @param  [type] $post_data [description]
     * @return [type]            [description]
     */
    public function curlSms($postUrl, $post_data)
    {
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);

        trace($postUrl . PHP_EOL . "上传数据" . json_encode($post_data, JSON_UNESCAPED_UNICODE), "send");

        curl_setopt($curl, CURLOPT_URL, $postUrl);

        curl_setopt($curl, CURLOPT_POST, 1);

        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($curl, CURLOPT_USERAGENT, "TEST");

        $result = curl_exec($curl);

        trace("上传结果" . $result, "send");

        $error = curl_error($curl);

        $result = json_decode($result, true);

        //关闭URL请求
        curl_close($curl);

        return ['result' => $result, 'error' => $error];
    }
}
require_once Env::get('vendor_path') . 'PHPExcel/PHPExcel.php';
/**
 * 读取excel过滤器类 单独文件
 */
class PHPExcelReadFilter implements \PHPExcel_Reader_IReadFilter
{

    public $startRow = 1;
    public $endRow;

    public function readCell($column, $row, $worksheetName = '')
    {
        if (!$this->endRow) {
            return true;
        }

        if ($row >= $this->startRow && $row <= $this->endRow) {
            return true;
        }

        return false;
    }

}
